<template>
  <div class="page-container">
    <div class="common-content-wrap">
      <TrTable
        ref="trTable"
        isNeedSelection
        :btnList="btnList"
        :total="totalNum"
        v-model="searchParams"
        :searchShowList="searchShowList"
        :searchHideList="searchHideList"
        :tableColumn="tableColumn"
        requestName="searchHandle"
        :tableData="tableData"
        @add="operateHandle($event, 'add')"
        @rowEdit="operateHandle($event, 'rowEdit')"
        @view="operateHandle($event, 'view')"
        @enable="operateHandle($event, 'enable')"
        @unEnable="operateHandle($event, 'unEnable')"
        @export="operateHandle($event, 'export')"
        @rowEnable="operateHandle($event, 'rowEnable')"
        @rowUnEnable="operateHandle($event, 'rowUnEnable')"
      />
    </div>

    <TrEditPopup
      ref="TrEditPopup"
      :width="460"
      v-model="isShowEdit"
      :title="checkTitle"
      :valueObj.sync="formObj"
      :formData="formData"
      :list="popupList"
      :relationList="relationList"
      @select-change="changeSelectHandle"
      @close="isShowEdit = false"
      @confrim="editConfirmHandle"
    />

    <TrDetail
      v-model="isShowDetailPopup"
      :leftList="detailList"
      statusModel="hidden"
      :detailData="detailData"
      :isNeedFooter="false"
      @close="closeDetailPopup"
    />
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  updateStatus,
  getLineNameInOrg,
  // getDeviceNameList,
} from "@/api/baseCode/workStation";
import { findByProperty } from "@/utils/util";
import { getColor } from "@/utils/billColor";
import { getStore } from "@/utils/store";
import enumData from "@/utils/enumCode.js";
import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrEditPopup from "@/components/Tr-form/Tr-form-popup.vue";
import TrDetail from "@/components/Tr-detail/Tr-detail.vue";

export default {
  components: {
    TrTable,
    TrEditPopup,
    TrDetail,
  },
  name: "WorkStationBox",
  data: () => ({
    tableColumn: [
      {
        type: "text",
        label: "工站编码",
        value: "stationCode",
      },
      {
        type: "text",
        label: "工站名称",
        value: "stationName",
      },
      {
        type: "text",
        label: "工站描述",
        value: "remark",
      },
      {
        type: "text",
        label: "线体名称",
        value: "lineName",
      },
      {
        type: "text",
        label: "车间",
        value: "workshopName",
      },
      {
        type: "text",
        label: "工序名称",
        value: "processName",
      },
      {
        type: "text",
        label: "机台号",
        value: "machineCode",
      },
      {
        type: "text",
        label: "状态",
        value: "isEnabledStr",
      },
      {
        type: "text",
        label: "创建人员",
        value: "createUserName",
      },
      {
        type: "text",
        label: "创建时间",
        value: "createTime",
      },
      {
        type: "text",
        label: "修改人员",
        value: "updateUserName",
      },
      {
        type: "text",
        label: "修改时间",
        value: "updateTime",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 120,
        showBtnList: [
          {
            label: "查看",
            option: "view",
          },
        ],
        hideBtnList: [
          {
            label: "启用",
            option: "rowEnable",
          },
          {
            label: "停用",
            option: "rowUnEnable",
          },
          {
            label: "编辑",
            option: "rowEdit",
          },
        ],
      },
    ],
    searchHideList: [
      {
        id: "stationCode",
        type: "input",
        width: 33.33,
        label: "工站编码",
        value: "",
      },
      {
        id: "stationName",
        type: "input",
        width: 33.33,
        label: "工站名称",
        value: "",
      },
      {
        id: "prodOrgId",
        type: "loadselect",
        width: 33.33,
        label: "所属车间",
        value: "",
        list: [],
        requestObj: {
          url: "/api/trio-system/prod-org/find-all-workshop",
          method: "post",
          searchKey: "orgName",
          rlLabel: "orgName",
          rlValue: "id",
          resultKey: "data,data",
        },
        defaultParams: {
          factoryId: getStore({ name: "factoryId" }),
        },
      },
      {
        id: "lineName",
        type: "input",
        width: 33.33,
        label: "线体名称",
        value: "",
      },
      {
        id: "isEnabledList",
        type: "multiSelect",
        list: [],
        width: 33.33,
        label: "工站状态",
        value: [],
      },
      {
        id: "deviceId",
        type: "loadselect",
        width: 33.33,
        label: "机台号",
        value: "",
        requestObj: {
          url: "/api/mes-equipment-service/device-ledger/machineCode/dropDown/page",
          method: "post",
          searchKey: "machineCode",
          rlLabel: "machineCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {
          filterHasRelatedStation: false,
        },
      },
      {
        startStr: "updateStartTime",
        endStr: "updateEndTime",
        id: "modifyTime",
        type: "daterange",
        width: 80,
        label: "修改时间",
        value: [],
        timePeriod: true,
        radio: -1,
      },
    ],
    searchShowList: [
      {
        isNeed: true,
        startStr: "createStartTime",
        endStr: "createEndTime",
        id: "createdTime",
        type: "daterange",
        width: 80,
        label: "创建时间",
        value: [],
        timePeriod: true,
        radio: 3,
      },
    ],
    btnList: [
      {
        label: "新增",
        option: "add",
        color: "blue",
      },
      {
        label: "启用",
        option: "enable",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "停用",
        option: "unEnable",
        color: "white",
        isRelaTable: true,
      },
      // {
      //   label: "导出",
      //   option: "export",
      //   color: "white",
      // },
    ],
    tableData: [],
    searchParams: {
      current: 1,
      size: 10,
    },
    totalNum: 0,

    detailData: {},
    isShowDetailPopup: false,
    detailList: [
      {
        type: "text",
        label: "基础信息",
        list: [
          {
            text: "工站名称",
            id: "stationName",
            width: 50,
          },
          {
            text: "工站编码",
            id: "stationCode",
            width: 50,
          },
          {
            text: "线体名称",
            id: "lineName",
            width: 50,
          },
          {
            text: "车间",
            id: "workshopName",
            width: 50,
          },
          {
            text: "工序名称",
            id: "processName",
            width: 50,
          },
          {
            text: "机台号",
            id: "machineCode",
            width: 50,
          },
          {
            text: "工站状态",
            id: "isEnabledStr",
            width: 50,
          },
          {
            text: "工站描述",
            id: "remark",
            width: 100,
          },
        ],
      },
    ],

    // 新增编辑弹窗
    formObj: {},
    formData: {},
    popupList: [
      {
        label: "工站编码",
        type: "input",
        width: 100,
        value: "",
        id: "stationCode",
        disabled: false,
      },
      {
        label: "工站名称",
        type: "input",
        width: 100,
        value: "",
        id: "stationName",
      },
      {
        label: "工序名称",
        type: "loadselect",
        width: 100,
        value: "",
        list: [],
        id: "processId",
        reviewLabel: "processName",
        requestObj: {
          url: "/api/mes-production-service/process/page",
          method: "post",
          searchKey: "processName",
          rlLabel: "processName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {
          isEnabledList: [1],
        },
      },
      {
        label: "车间名称",
        type: "loadselect",
        width: 100,
        value: "",
        list: [],
        id: "prodOrgId",
        selectedLabel: "",
        reviewLabel: "prodOrgName",
        requestObj: {
          url: "/api/trio-system/prod-org/find-all-workshop",
          method: "post",
          searchKey: "orgName",
          rlLabel: "orgName",
          rlValue: "id",
          resultKey: "data,data",
        },
        defaultParams: {
          factoryId: getStore({ name: "factoryId" }),
        },
      },
      {
        label: "线体名称",
        type: "loadselect",
        width: 100,
        value: "",
        list: [],
        id: "lineId",
        reviewLabel: "lineName",
        isNeed: false,
        requestObj: {
          url: "/api/mes-production-service/line/page",
          method: "post",
          searchKey: "lineName",
          rlLabel: "lineName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {
          isEnabled: [1],
          prodOrgId: "",
        },
      },
      {
        label: "机台号",
        type: "loadselect",
        width: 100,
        value: "",
        list: [],
        id: "deviceId",
        isNeed: false,
        selectedLabel: "",
        reviewLabel: "machineCode",
        requestObj: {
          url: "/api/mes-equipment-service/device-ledger/machineCode/dropDown/page",
          method: "post",
          searchKey: "machineCode",
          rlLabel: "machineCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {
          filterHasRelatedStation: true,
        },
      },
      {
        label: "是否启用",
        type: "radio",
        width: 100,
        value: 1,
        id: "isEnabled",
        list: [
          { label: "是", value: 1 },
          { label: "否", value: 0 },
        ],
        isNeed: false,
      },
      {
        isNeed: false,
        label: "工站描述",
        type: "textarea",
        maxlength: 100,
        width: 100,
        value: "",
        id: "remark",
      },
    ],
    relationList: [
      {
        id: "lineId",
        relaList: [
          {
            disabled: false,
            isNotStrict: true,
            relaId: "prodOrgId",
            relaValue: "prodOrgId",
            relaLabel: "prodOrgName",
          },
        ],
      },
      {
        id: "prodOrgId",
        relaList: [
          {
            disabled: false,
            relaId: "lineId",
            relaValue: "lineId",
            relaLabel: "lineName",
            params: [
              {
                labelWord: "prodOrgId",
                realWord: "rlValue",
                editWord: "prodOrgId",
              },
            ],
          },
        ],
      },
    ],
    isShowEdit: false,
    currentHandle: "",
    currentRowVal: {},
  }),
  computed: {
    checkTitle() {
      const titles = {
        add: "新增",
        default: "编辑",
      };
      return titles[this.currentHandle] || titles.default;
    },
    ids() {
      let ids = [];
      this.$refs.trTable.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
  },
  mounted() {
    // this.getListHandle();
    this.getEnmuData();
  },
  methods: {
    changeSelectHandle(val, item) {
      // if (val.ftId == "lineId") {
      //   let prodOrg = this.$findByProperty(this.popupList, "id", "prodOrgId");
      //   this.$set(prodOrg, "value", val.prodOrgId);
      //   this.$set(prodOrg, "selectedLabel", val.prodOrgName);
      //   this.$refs.TrEditPopup.outReset("prodOrgId", prodOrg);
      //   console.log(prodOrg);
      // }
      console.log(val, item);
    },
    operateHandle(val, type) {
      console.log(val, type, "val, type");
      this.currentHandle = type;

      const stationCodeItem = findByProperty(
        this.popupList,
        "id",
        "stationCode"
      );
      const col = this.$findByProperty(
        this.detailList,
        "id",
        "isEnabledStr",
        "list"
      );
      col.valueColor =
        {
          1: "#00A870",
          0: "#E34D59",
        }[val.isEnabled] || "";
      this.$validateData(val, 3);
      this.formData = type == "rowEdit" ? val : {};
      const actions = {
        add: () => {
          this.formData = {};
          let lineCol = findByProperty(this.popupList, "id", "lineId");
          lineCol.defaultParams.prodOrgId = "";
          stationCodeItem.disabled = false;
          this.isShowEdit = true;
        },
        rowEdit: async () => {
          if (val.lineId && val.lineId != "-") {
            await this.getLineNameInOrgHandle(val.lineName);
          }

          this.currentRowVal = val;
          stationCodeItem.disabled = true;
          this.isShowEdit = true;
        },
        view: () => this.getDetailHandle(val),
        enable: () => this.updateLineStatus(this.ids, 1, "tip.enableTip"),
        unEnable: () => this.updateLineStatus(this.ids, 0, "tip.unenableTip"),
        export: () =>
          this.$exportHandle({ vm: this, params: this.searchParams }),
        rowEnable: () => this.updateLineStatus([val.id], 1, "tip.enableTip"),
        rowUnEnable: () =>
          this.updateLineStatus([val.id], 0, "tip.unenableTip"),
      };

      const action = actions[type];
      if (action) action();
    },
    // 新增的辅助方法
    async updateLineStatus(idList, status, tipKey) {
      const result = await this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t(tipKey)],
      });
      if (!result) return;

      const { data } = await updateStatus({ idList, enable: status });
      if (data.code !== 200) return;
      this.$refs.trTable.clearSelect();
      this.$message.success(this.$t("msg.success"));
      this.searchParams.current = 1;
      this.getListHandle();
    },
    async getDetailHandle(val) {
      const { data } = await getDetail(val.id);

      if (data.code !== 200) return;

      this.$validateData(data.data);

      this.detailData = data.data;

      this.isShowDetailPopup = true;
    },
    async getLineNameInOrgHandle(lineName) {
      const { data } = await getLineNameInOrg({
        current: 1,
        size: 10,
        lineName,
      });
      if (data.code !== 200) return;
      let dataTemp = data.data.records[0];
      let lineCol = findByProperty(this.popupList, "id", "lineId");
      lineCol.defaultParams.prodOrgId = dataTemp.prodOrgId;
      this.formData.prodOrgId = dataTemp.prodOrgId;
      this.formData.prodOrgName = dataTemp.prodOrgName;
    },
    closeDetailPopup() {
      this.isShowDetailPopup = false;
    },
    async getEnmuData() {
      const { ["PC-ENABLED-LIST"]: enable } = await this.$fetchEnumData([
        enumData.isEnabledList,
      ]);
      let enableItem = findByProperty(
        this.searchHideList,
        "id",
        "isEnabledList"
      );
      let enmudata = enable.map((item) => {
        return {
          ...item,
          checked: false,
        };
      });
      this.$set(enableItem, "list", enmudata);
    },
    searchHandle() {
      this.getListHandle();
    },
    async getListHandle() {
      const { data } = await getList(this.searchParams);
      if (data.code != 200) return;
      this.$validateData(data.data);
      this.tableData = data.data.records;
      this.tableData.forEach((item) => {
        item["isEnabledStrColor"] = getColor("QT", item.isEnabled);
      });
      this.totalNum = Number(data.data.total);
    },
    async addConfirmHandle() {
      const { data } = await add(this.formObj);
      return data.code === 200;
    },
    async editHandle() {
      const { data } = await update({
        ...this.formObj,
        id: this.currentRowVal.id,
      });
      return data.code === 200;
    },
    async editConfirmHandle() {
      let flag = false;
      if (this.formObj.lineId != "") {
        //当线体不为空时，车间不需要传给后端（后端校验要求）
        this.formObj.prodOrgId = null;
      }

      if (this.currentHandle === "add") {
        flag = await this.addConfirmHandle();
      } else {
        flag = await this.editHandle();
      }
      if (!flag) return;
      this.$message.success(this.$t("msg.success"));
      this.isShowEdit = false;
      this.searchParams.current = 1;
      this.getListHandle();
    },
  },
};
</script>
